<template>
  <div>
    <FormDialogComponent
      ref="formtDialogRef"
      dialogWidth="800px"
      v-model="form"
      :formInline="false"
      dialogTitle="生产操作"
      :autoTitle="false"
      :formHeader="formHeader"
      :formUrl="formUrl"
      :showFormFoot="false"
      :formAction="formAction"
      @dialogClosed="dialogClosed"
      @beforeFormSubmit="beforeFormSubmit"
      @afterFormSubmitFailure="afterFormSubmitFailure"
      @afterSubmitSuccess="afterSubmitSuccess"
    >
      <template #form_vin>
        <el-input v-model="form.productionOrder!.vin" :disabled="true" style="width: 400px" />
      </template>
      <template #form_materialName>
        <el-input v-model="form.carTechnologyDetail!.material!.name" :disabled="true" style="width: 400px" />
      </template>
      <!-- 物料批次选择框 -->
      <template #form_materialBatchId="scope">
        <MaterialBatchSelectComponent
          width="500px"
          :materialId="form.carTechnologyDetail!.material!.id"
          :materialNameType="2"
          v-model="form['materialBatchId']"
          v-model:materialName="form['materialName']"
          @afterClickSelectButton="formtDialogRef.clearFieldValidation('materialBatchId')"
          @closed="formtDialogRef.fieldValidation('materialBatchId')"
          @afterSelectMaterialBatch="afterSelectMaterialBatch"
          :readonly="scope.item.disabled"
        />
      </template>
      <!--计划用量-->
      <template #form_planQuantity>
        <el-input v-model="form.carTechnologyDetail!.quantity" :disabled="true" style="width: 400px" />
      </template>
    </FormDialogComponent>
  </div>
</template>

<script setup lang="ts">
import FormDialogComponent from '@/components/base/table/form/FormDialogComponent.vue';
import MaterialBatchSelectComponent from '@/components/wms/MaterialBatchSelectComponent.vue';
import ProductionOrderStepTable from '@/views/page/mes/productionorder/ProductionOrderStepTable.vue';
import type { FormHeader, TableData } from '@/types/interface/base_interface';
import { nextTick, onMounted, ref } from 'vue';
import urls from '@/api/request/urls';
import Request from '@/api/request/request';
import type { ProductionOrder, ProductionOrderStep } from '@/types/interface/mes_interface';
import { getDict, type Option } from '@/api/dict';
import type { MaterialBatch } from '@/types/interface/wms_interface';
const emit = defineEmits(['afterSubmitSuccess']);

// 接收父容器参数
interface Props {
  action?: string; // 表单的处理类型，post表示提交，put表示编辑
}
const props = withDefaults(defineProps<Props>(), {
  action: 'put'
});

let productionOrderStepId: string | undefined; //生产订单步骤的ID
let operatorType: number | undefined; //操作类型，是完成工作还是审核
// let auditResult: string | undefined; //用于记录审核结果，配合表单提交成功失败后重置使用。
// let auditNote: string | undefined; //用户记录审核意见，配合表单提交成功失败后重置使用。

//表单==========================================================
//表单对象
const form = ref<ProductionOrderStep>({});
//表单元素类型
const formHeader = ref<FormHeader[]>([]);
//表单提交
let formUrl: string = urls.API_URL_BACKSTAGE_MES_PRODUCTIONORDERSTEP;
//表单提交方式
let formAction: string = 'put';
//下拉框的值
let productionOrderStepStatusDict: Array<Option>; //生产订单步骤状态字典
let auditDict: Array<Option>; //审核状态字典

onMounted(async () => {
  //下拉框
  productionOrderStepStatusDict = await getDict('汽车生产订单步骤状态', 'string');
  auditDict = await getDict('审核状态', 'boolean');
  // 添加编辑表单,通过函数动态变化
});
//===================================对话框====================================================
const formtDialogRef = ref();
//生成完成工作的表单结构
const initCompletedWorkFormStructure = () => {
  formHeader.value = [
    {
      label: 'VIN',
      prop: 'vin',
      type: 'custom',
      disabled: true
    },
    {
      label: '物料',
      prop: 'materialName',
      type: 'custom',
      disabled: true
    },
    {
      label: '物料批次',
      prop: 'materialBatchId',
      type: 'custom',
      rules: [
        {
          required: true,
          message: '不能为空',
          trigger: 'blur'
        }
      ]
    },

    {
      label: '计划用量',
      prop: 'planQuantity',
      type: 'custom',
      disabled: true
    },
    {
      label: '实际用量',
      prop: 'actualQuantity',
      type: 'number',
      config: {
        number: {
          min: 0
        }
      },
      width: '400px',
      rules: [
        {
          required: true,
          message: '不能为空',
          trigger: 'blur'
        }
      ]
    },
    {
      label: '生产状态',
      prop: 'status',
      type: 'select',
      width: '400px',
      list: productionOrderStepStatusDict,
      disabled: true
    }
  ];
};
//生成审核工单的表单结构
const initAuditFormStructure = () => {
  formHeader.value = [
    {
      label: 'VIN',
      prop: 'vin',
      type: 'custom',
      disabled: true
    },
    {
      label: '物料',
      prop: 'materialName',
      type: 'custom',
      disabled: true
    },
    {
      label: '物料批次',
      prop: 'materialBatchId',
      type: 'custom',
      disabled: true
    },

    {
      label: '计划用量',
      prop: 'planQuantity',
      type: 'custom',
      disabled: true
    },
    {
      label: '实际用量',
      prop: 'actualQuantity',
      type: 'number',
      config: {
        number: {
          min: 0
        }
      },
      width: '400px',
      disabled: true
    },
    {
      label: '生产状态',
      prop: 'status',
      type: 'select',
      width: '400px',
      list: productionOrderStepStatusDict,
      disabled: true
    },
    {
      label: '审核结果',
      prop: 'auditResult',
      type: 'select',
      list: auditDict,
      width: '400px',
      rules: [
        {
          required: true,
          message: '不能为空',
          trigger: 'blur'
        }
      ]
    },
    {
      label: '审核意见',
      prop: 'auditNote',
      type: 'textarea',
      width: '400px'
    }
  ];
};
//初始化表单信息
const initForm = async (type: number | undefined) => {
  if (type == undefined || type == 1) {
    //初始化表单结构
    initCompletedWorkFormStructure();
    //继续初始化表单
    //传入初始值
    if (form.value) {
      if (form.value.actualQuantity == undefined || form.value.actualQuantity == null) {
        form.value.actualQuantity = 0;
      }
      //如果物料批次存在，则设置物料id
      if (form.value.materialBatch) {
        form.value.materialBatchId = form.value.materialBatch?.id;
      }
      //如果物料批次存在，则设置物料名
      // if (form.value.materialBatch != null) {
      //   form.value.materialName = form.value.materialBatch.material!.name;
      // }
    }
    formUrl = urls.API_URL_BACKSTAGE_MES_PRODUCTIONORDERSTEP;
    formAction = 'put';
  } else if (type == 2) {
    //初始化表单结构
    initAuditFormStructure();
    //初始化物料批次的值
    form.value.materialBatchId = form.value.materialBatch?.id;
    formUrl = urls.API_URL_BACKSTAGE_MES_PRODUCTIONORDERSTEP_AUDIT;
    formAction = 'patch';
    // await nextTick();
    //重置表单，移除上一次打开的审核属性。
    delete form.value.auditResult;
    delete form.value.auditNote;
    //审核表单
    //首先移除审核表单的form
    // formHeader.value = formHeader.value.filter((item) => item.prop !== 'auditNote' && item.prop !== 'auditResult');
  }
};
//加载生产订单
const loadProductionOrderStep = async (id: string) => {
  const resData: any = await new Request(`${urls.API_URL_BACKSTAGE_MES_PRODUCTIONORDERSTEP}/${id}`).get();
  if (resData.success) {
    form.value = resData.data;
  }
};
/**
 * 打开对话框，根据传入的业务进行操作
 * @param id
 * @param type 1表示完成生产步骤、2表示审核生产步骤
 */
const openDialog = async (id: string, type: number | undefined) => {
  //获取生产订单步骤id
  productionOrderStepId = id;
  operatorType = type;
  //加载生产订单信息
  await loadProductionOrderStep(id);
  //初始化表单结构和初始值
  await initForm(type);
  //加载完数据再打开对话框
  await formtDialogRef.value.openDialog();
};
const closeDialog = () => {
  //关闭对话框
  formtDialogRef.value.closeDialog();
};
//添加表单关闭后触发
const dialogClosed = async () => {
  //通过重新赋值，重置物料信息
};
//在表单提交前要处理的事
const beforeFormSubmit = async () => {
  //避免添加失败后物料的materialBatch因没有重新选择批次导致没有传值
  if (form.value.materialBatchId && !form.value.materialBatch) {
    form.value.materialBatch = {
      id: form.value.materialBatchId
    };
  }
  //封装要提交的对象。
};
//在表单提交失败后
const afterFormSubmitFailure = async () => {
  //重新渲染批次选择的ID
  let materialBatch, actualQuantity, auditResult, auditNote;
  //如果物料批次存在，则设置物料id
  if (form.value.materialBatch) {
    //如果已经选择了物料，则设置物料选择框的值
    materialBatch = form.value.materialBatch;
  }
  //如果物料数量存在
  if (form.value.actualQuantity) {
    actualQuantity = form.value.actualQuantity;
  }
  //如果审核意见存在，说明目前是审核表单
  if (form.value.auditResult) {
    auditResult = form.value.auditResult;
    auditNote = form.value.auditNote;
  }
  //重新加载原来的生产订单信息
  await loadProductionOrderStep(form.value.id!);
  //重新加载后，将原来填写的错误的表单信息恢复
  //重置物料批次
  if (materialBatch) {
    form.value.materialBatchId = materialBatch.id;
  }
  if (actualQuantity) {
    form.value.actualQuantity = actualQuantity;
  }
  //重置审核信息
  if (auditResult) {
    //如果审核意见存在，说明目前是审核表单
    form.value.auditResult = auditResult;
    form.value.auditNote = auditNote;
  }
};
//表单提交成功后
const afterSubmitSuccess = () => {
  //表单成交提供后的回调
  emit('afterSubmitSuccess');
};
//在选择物料批次后
const afterSelectMaterialBatch = async (materialBatchs: MaterialBatch[]) => {
  //将当前选择的物料批次返回
  if (materialBatchs.length > 0) {
    //获取物料批次
    form.value.materialBatch = materialBatchs[0];
  }
};
defineExpose({
  // 参考vue3官方文档，需要将函数暴露出去才能被父组件调用，setup模式是不暴露的
  openDialog,
  closeDialog
});
</script>

<style scoped></style>
